<?php
declare (strict_types = 1);
namespace app\api\controller;

use app\api\controller\BaseController;
use service\JsonService as Json;
use think\exception\ValidateException;

use think\facade\{Db, Cache, Log};

use app\common\model\{User, Code};
use app\common\validate\{UserValidate};

class LoginController extends BaseController
{
    /** 登录 */
    public function login()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('login')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        /** 校验验证码 */
        // $isCode = Code::checkCode($data['mobile'], $data['code']);
        // if($isCode !== true) return Json::fail($isCode);

        $userInfo = User::getFind(['mobile' => $data['mobile']]);

        if($userInfo === false) return Json::fail('手机号不存在');

        $backData['token'] = $this->jwt($userInfo['id']);
        User::editWhere(['token' => $backData['token']], ['mobile' => $data['mobile']]);

        return Json::success('登录成功', $backData);
    }

    /** 注册 */
    public function register()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('register')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        /** 校验验证码 */
        $isCode = Code::checkCode($data['mobile'], $data['code']);
        if($isCode !== true) return Json::fail($isCode);

        /** 检查手机号是否已存在 */
        $userInfo = User::getFind(['mobile' => $data['mobile']]);
        if($userInfo !== false) return Json::fail('手机号已存在');

        $data['money']           = 0;
        $data['money_brokerage'] = 0;
        $data['money_red']       = 0;
        $data['point']           = 0;

        $addFlag = User::add($data);

        if($addFlag === false) return Json::fail('注册失败');

        return Json::success('注册成功');
    }

    /** 获取openid */
    public function getOpenId()
    {
        $wxCode = Request()->param('wx_code', '');
        $system = getSystemVal();

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$system['appid']}&secret={$system['appsecret']}&js_code={$wxCode}&grant_type=authorization_code";
        $res = curl_get($url);
        $res = json_decode($res, TRUE);

        if(isset($res['errcode'])){
            return Json::fail($res['errmsg']);
        }else{
            User::edit(['id' => $this->user_id, 'openid' => $res['openid']]);
            return Json::success('ok', $res);
        }
    }

    /** 发送验证码 */
    public function sendSms()
    {
        $data = input('post.');

        try{
            validate(UserValidate::class)->scene('mobile')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $info = Code::getFind(['mobile' => $data['mobile'], 'is_use' => 0], '*', 'id desc');

        // 5分钟内重复提交
        if ($info !== false && $info['expiration_time'] -  5 * 60 > time()){
            return Json::fail("验证码已发送");
        }

        // 验证码
        $data['code'] = rand(1111, 9999);

        $codeFlag = sendSms($data['mobile'], $data['code']);

        // 过期时间
        $data['expiration_time'] = strtotime('+5 minute');

        $flag = Code::add($data);

        if($flag == false){
            return Json::fail('验证码发送失败');
        }

        return Json::success('验证码发送成功');
    }

    /** 数据库初始化 */
    public function del()
    {
        $h = 'l_';

        Db::execute("truncate table ". $h . "apply");
        Db::execute("truncate table ". $h . "cash");
        Db::execute("truncate table ". $h . "banner");
        Db::execute("truncate table ". $h . "cash");
        Db::execute("truncate table ". $h . "financial_record");
        Db::execute("truncate table ". $h . "img");
        Db::execute("truncate table ". $h . "order");
        Db::execute("truncate table ". $h . "product");
        Db::execute("truncate table ". $h . "product_cate");
        Db::execute("truncate table ". $h . "product_sku");
        Db::execute("truncate table ". $h . "user");
        Db::execute("truncate table ". $h . "user_address");
    }
}